import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

service.interceptors.request.use(config => {
  const mytoken = localStorage.getItem('mytoken')
  if (mytoken && !config.noToken) {
    const timeout = 1000 * 60 * 60 * 3
    const loginTime = localStorage.getItem('loginTime')
    const now = Date.now()
    // console.log(17, now)
    if (now - loginTime > timeout) {
      // 过期
      // 跳转登录页
      router.push('/login')
      // 阻止当前异步请求
      console.log('执行')
      localStorage.removeItem('mytoken')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('loginTime')
      return Promise.reject(new Error('token 失效'))
    }
    config.headers.Authorization = mytoken
  }
  return config
})

service.interceptors.response.use(res => {
  // console.log('网络层面成功', res)
  // 结构 res.data 里面的数据继续判断

  return res
}, err => {
  // console.log('网络层面的失败', err)
  // console.dir(err)
  // 这里是拦截所有网络错误的地方
  // 我们跟后端约定，如果是token 相关
  // 报出来的 err.response.data.code === 10002
  // console.log(45, err.response.data.message[0].messages[0].message)
  console.log(45, err.response)
  var errtips = err.response.data.message[0].messages[0].message
  // if(err.response.data.statusCode !== 200){
  const meiju = [{
    EN: 'Identifier or password invalid.',
    ZH: '账号或者密码有误~~~~~~~'
  }]
  meiju.forEach(item => {
    if (item.EN === errtips) {
      errtips = item.ZH
    }
  })

  // }
  Message.error(errtips)
  return Promise.reject(new Error(err.message))
})

export default service
